package com.sso.config;

import com.sso.security.handler.LoginFailureHandler;
import com.sso.security.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Author: TongRui乀
 * @Date: 2020-03-23 14:46
 * @description： SpringSecurity 安全配置
 */
@Order(2) // 先与 ResourceServer 过滤
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *  登录成功的处理逻辑
     */
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    /**
     *  登录失败的处理逻辑
     */
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    /**
     *  自定义查询用户信息逻辑
     */
    @Autowired
    private UserDetailsService customerUserDetailService;

    /*@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .formLogin()
                .loginPage("/preLoginHandler")
                .loginProcessingUrl("/authentication/form")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
            .and()
            .authorizeRequests()
                .antMatchers("/preLoginHandler", "/oauth/authorize", "/login.html").permitAll() // 不拦截的请求
                .anyRequest()
                .authenticated()
            .and()
            .csrf()
                .disable();

    }*/


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().and().authorizeRequests().anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(customerUserDetailService); // 使用自定义的用户查询逻辑
    }

    /**
     *  加密器
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     *  密码模式需要使用
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
